//
//  SearchDetailViewController.m
//  Travel
//
//  Created by dllo on 15/10/6.
//  Copyright (c) 2015年 0. All rights reserved.
//

#import "SearchDetailViewController.h"
//#import "HotTravelPlaceViewController.h"
#import "desDetilCell.h"
//#import "desdetailTableViewCell.h"
#import "desDetailModle.h"
#import "UIImageView+WebCache.h"
#import "HTTPTool.h"
#import "DetailFirstViewController.h"
#import "TravelNoteViewController.h"
#import <MBProgressHUD.h>
//#import "TravelNoteViewController.h"
#import "UseWebViewController.h"
//#import "SpecialWebViewController.h"
#import "ImageViewController.h"
#import "SearchCollectionReusableView.h"

#import "BaseView.h"



@interface SearchDetailViewController () <UICollectionViewDataSource,UICollectionViewDelegate>

@property(nonatomic,retain)UICollectionView *collectionView;
@property(nonatomic,retain)NSMutableArray *colArr;
@property(nonatomic,retain)NSMutableArray *picArr;
@property(nonatomic,retain)UIImageView *imageViews;

@property(nonatomic,retain)SearchCollectionReusableView *reusableView;
@property(nonatomic,retain)MBProgressHUD *HUD;
@end

@implementation SearchDetailViewController

-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    //数组初始化
    self=[super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if(self){
        self.colArr=[NSMutableArray array];
        self.picArr = [NSMutableArray array];
       
    }
    
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //self.navigationItem.title = self.titleName;
    self.view.backgroundColor=[UIColor clearColor];

    self.automaticallyAdjustsScrollViewInsets = NO;
    NSDictionary *dict = [NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:NSForegroundColorAttributeName];
    self.navigationController.navigationBar.titleTextAttributes = dict;

    
    self.collectionView.autoresizesSubviews = NO;
    //返回键
    UIImage *leftImage = [UIImage imageNamed:@"导航栏_button_back_用于白和灰.png"];
    leftImage = [leftImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:leftImage style:UIBarButtonItemStylePlain target:self action:@selector(leftButtonAction)];
    
 
    
    //创建瀑布流效果
    UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init];
    //每一个item的大小
    flowLayout.itemSize=CGSizeMake((WIDTH - 30) / 2, (WIDTH - 30) / 2);
    flowLayout.headerReferenceSize = CGSizeMake(WIDTH, 110*XHIGHT);

    //设置最小的行间距
    flowLayout.minimumLineSpacing = 0;
    //设置最小的列间距
    flowLayout.minimumInteritemSpacing = 0;
    //滑动的方向(垂直滑动),默认是垂直滑动
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    //边缘
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 15, 10, 10);
    //创建瀑布流视图
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0,0, WIDTH, HIGHT - 64) collectionViewLayout:flowLayout];
    //签订两个协议,一个dataSource,一个delegate
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    //相对于0点,已经向下偏移了-200
    
   
    //把瀑布流视图添加到view上
//    [self.desDetialTableView addSubview:self.collectionView];
    //设置瀑布流的背景颜色
    self.collectionView.backgroundColor=[UIColor whiteColor];
    
    [self.view addSubview:self.collectionView];
    
    //注册
    //第一个参数:需要指定注册的类型;第二个参数:重用标志
    
    [self.collectionView registerClass:[desDetilCell class] forCellWithReuseIdentifier:@"reuse"];
    [self.collectionView registerClass:[SearchCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView"];
    
    
    
    [self createData:2];


}
-(void)leftButtonAction
{
    [self.navigationController popToRootViewControllerAnimated:NO];
}
-(void)createData:(NSInteger)pageNum
{
    
    
    [HTTPTool get:[NSString stringWithFormat:@"http://api.breadtrip.com/destination/place/%@/%@/pois/all/?sort=default&start=0&latitude=38.883740&longitude=121.544706&sign=8b29d40b1747a21dc6581e74e5a22fe4",self.typeNUmber,self.idString] body:nil httpResult:JSON success:^(id result) {
//        NSLog(@"----http://api.breadtrip.com/destination/place/%@/%@/pois/all/?sort=default&start=0&latitude=38.883740&longitude=121.544706&sign=8b29d40b1747a21dc6581e74e5a22fe4",self.typeNUmber,self.idString);
        NSDictionary *dic = result;
        NSArray *dataArr=dic[@"items"];
        if (dataArr.count != 0) {
            for (NSDictionary *temp in dataArr) {
                desDetailModle *cover = [[desDetailModle alloc] init];
                cover.bId = [temp objectForKey:@"id"];
                [cover setValuesForKeysWithDictionary:temp];
                [self.colArr addObject:cover];
               
                
            }

        }
       
        //相对于0点,图片坐标应该是(0,-200)
        self.collectionView.contentInset = UIEdgeInsetsMake(200.0*XHIGHT, 0, 0, 0);

        self.imageViews = [[UIImageView alloc] initWithFrame:CGRectMake(0, -200.0*XHIGHT, 375*XWIDTH, 200.0*XHIGHT)];
        [self.imageViews sd_setImageWithURL:[NSURL URLWithString:self.url] placeholderImage:nil];
        //设置imageView高度改变时宽度也跟着改变
        self.imageViews.contentMode = UIViewContentModeScaleAspectFill;
        self.imageViews.layer.masksToBounds = YES;
        [self.collectionView addSubview:self.imageViews ];
        //imageView添加点击事件
        [self.imageViews setUserInteractionEnabled:YES];
        [self.imageViews addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickCategory:)]];
        [self.collectionView reloadData];
        
       
        
        
    }
          failure:^(NSError *error) {
              
              //NSLog(@"%@",error);
          }];
    
    
    
    [HTTPTool get:[NSString stringWithFormat:@"http://api.breadtrip.com/destination/place/%@/%@/",self.typeNUmber,self.idString] body:nil httpResult:JSON success:^(id result) {
        //NSLog(@"%@   %@",self.typeNUmber,self.idString);
        NSDictionary *dic = result;
        NSArray *arr=dic[@"hottest_places"];
        if (arr.count != 0) {
            for (NSDictionary *temp in arr) {
                desDetailModle *cover=[[desDetailModle alloc]init];
                [cover setValuesForKeysWithDictionary:temp];
                [self.picArr addObject:cover];
                
            }

        }
        self.titleName = dic[@"name_orig"];
        self.visitCount = [NSString stringWithFormat: @"%@",dic[@"visited_count"]];
        self.wishCount = [NSString stringWithFormat: @"%@",dic[@"wish_to_go_count"]];
        
        
        [self.collectionView reloadData];
        [self.HUD removeFromSuperview];
        
    }
          failure:^(NSError *error) {
              //NSLog(@"%@",error);
          }];
    //菊花
    self.HUD=[[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.HUD];
    [self.HUD showAnimated:YES whileExecutingBlock:^{
        
    } completionBlock:^{
        [self.HUD show:NO];
        
    }];

    
    
    
}
-(void)clickCategory:(UITapGestureRecognizer *)gestureRecognizer
{
    NSLog(@"click");
    ImageViewController *detailVC = [[ImageViewController alloc]init];
    detailVC.idString = self.idString;
    detailVC.typeNUmber = self.typeNUmber;
    
    [self.navigationController pushViewController:detailVC animated:YES];
    
    
    
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    return self.colArr.count;
    
}

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (kind == UICollectionElementKindSectionHeader) {
        //代表是表头 headerView是表头重用标识符 kind代表区域类型是表头还是底部
        self.reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"headerView" forIndexPath:indexPath];
//        if (self.picArr.count != 0) {
//            desDetailModle *imagePic = [self.picArr objectAtIndex:0];
//            [self.reusableView.myImageView sd_setImageWithURL:[NSURL URLWithString:imagePic.photo] placeholderImage:[UIImage imageNamed:@"1.jpg"]];
//            
//        }
        
        //NSLog(@"??%ld",self.picArr.count);
        self.reusableView.nameLable.text = self.titleName;
        self.reusableView.wishLabel.text =[NSString stringWithFormat:@"%@去过 / %@喜欢",self.visitCount,self.wishCount];
//        [self.reusableView.placeButton addTarget:self action:@selector(placeAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.reusableView.noteButton addTarget:self action:@selector(noteAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.reusableView.useButton addTarget:self action:@selector(useButtonAction:) forControlEvents:UIControlEventTouchUpInside];
//        [self.reusableView.offerButton addTarget:self action:@selector(offerAction:) forControlEvents:UIControlEventTouchUpInside];
        

        return self.reusableView;
    }

    return nil;
}


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    desDetilCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath] ;
    //创建model对象
    if (self.colArr.count != 0) {
        desDetailModle *coverPic = self.colArr[indexPath.row];
        cell.myLable.text=coverPic.name;
        //用sdwebimage对imageview进行图片赋值
        [cell.myImageView1 sd_setImageWithURL:[NSURL URLWithString:coverPic.cover_route_map_cover]placeholderImage:[UIImage imageNamed:@"1.jpg"]];
    }
    return cell;
    
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //刚开始y的偏移量初始值就是-264
    NSLog(@"y1 === %f",scrollView.contentOffset.y);
    CGFloat y = scrollView.contentOffset.y;//加上导航栏高度,第一次是-200
    NSLog(@"y2 === %f",y);
    
    if (y < -200*XHIGHT) {
        CGRect frame = self.imageViews.frame;
        frame.origin.y = y;//imageView的frame是不断往上偏移
        frame.size.height =  -y ;//tablview向下偏移了多少,高度就增加多少
        self.imageViews.frame = frame;
        
        NSLog(@"%f",self.imageViews.frame.origin.y);
        NSLog(@"y=%f",y);
    }
    
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.colArr.count != 0) {
        DetailFirstViewController *detail = [[DetailFirstViewController alloc] init];
        desDetailModle *des = self.colArr[indexPath.row];
        detail.idString = des.bId;
        NSLog(@"des.bid=%@",des.bId);
        detail.typeNUmber = des.type;
        detail.url = des.cover;
        detail.title = des.name;
        self.navigationController.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:detail animated:NO];
       
    }
}

/*
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}
 */
/*
//旅行地点跳转
-(void)placeAction:(UIButton *)placeButton
{
    HotTravelPlaceViewController *TravelSite=[[HotTravelPlaceViewController alloc] init];
    TravelSite.idString=self.idString;
    TravelSite.typeNumber=self.typeNUmber;
    
    [self.navigationController pushViewController:TravelSite animated:YES];
}
*/
//精品游记跳转
-(void)noteAction:(UIButton *)noteButton
{
    TravelNoteViewController *noteTravel=[[TravelNoteViewController alloc] init];
    noteTravel.idString=self.idString;
    noteTravel.typeNumber=self.typeNUmber;
    [self.navigationController pushViewController:noteTravel animated:NO];
}

//实用须知跳转
-(void)useButtonAction:(UIButton *)useButton
{
    UseWebViewController *webVC = [[UseWebViewController alloc]init];
    webVC.url = self.webUrl;
    //NSLog(@"+++---%@",self.webUrl);
    [self.navigationController pushViewController:webVC animated:NO];
}
/*
//特价跳转
-(void)offerAction:(UIButton *)offButton
{
    SpecialWebViewController *webVC = [[SpecialWebViewController alloc]init];
    webVC.url = self.webUrl;
    [self.navigationController pushViewController:webVC animated:YES];
}
*/
 //跳转图片详情
//-(void)imageAction:(UIButton *)imageButton
//{
//     ImageViewController *imageVC = [[ImageViewController alloc] init];
//     imageVC.idString = self.idString;
//     imageVC.typeNUmber = self.typeNUmber;
//     [self.navigationController pushViewController:imageVC animated:YES];
//    //http://api.breadtrip.com/destination/place/1/JP/photos/?start=0&count=21&gallery_mode=true
//}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


@end
